package com.stenio.fancat.service.baby;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stenio.fancat.common.errorCode.ErrorCode;
import com.stenio.fancat.domain.PageList;
import com.stenio.fancat.domain.baby.BabyAccount;
import com.stenio.fancat.domain.baby.BabyIconImage;
import com.stenio.fancat.domain.baby.BabyPartner;
import com.stenio.fancat.domain.baby.BabyRelationship;
import com.stenio.fancat.domain.behavior.BehaviorOperationImage;
import com.stenio.fancat.domain.bo.UserRelationshipBO;
import com.stenio.fancat.domain.candy.Candy;
import com.stenio.fancat.domain.user.UserRelationship;
import com.stenio.fancat.domain.user.UserRelationshipCandy;
import com.stenio.fancat.domain.user.UserRelationshipLog;
import com.stenio.fancat.domain.user.UserRelationshipName;
import com.stenio.fancat.exception.FanCatException;
import com.stenio.fancat.form.baby.BabyAccountForm;
import com.stenio.fancat.form.user.UserRelationshipForm;
import com.stenio.fancat.mapper.Behavior.BehaviorLogMapper;
import com.stenio.fancat.mapper.Behavior.BehaviorOperationImageMapper;
import com.stenio.fancat.mapper.baby.BabyAccountMapper;
import com.stenio.fancat.mapper.baby.BabyIconImageMapper;
import com.stenio.fancat.mapper.baby.BabyPartnerMapper;
import com.stenio.fancat.mapper.baby.BabyRelationshipMapper;
import com.stenio.fancat.mapper.candy.CandyMapper;
import com.stenio.fancat.mapper.user.*;
import com.stenio.fancat.service.enums.AccountStatus;
import com.stenio.fancat.util.EmptyUtil;
import com.stenio.fancat.util.RedisUtil;
import com.stenio.fancat.util.StringUtil;
import com.stenio.fancat.vo.BabyAccountVO;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * baby基本信息类
 */
@Service
public class BabyAccountService extends ServiceImpl<BabyAccountMapper, BabyAccount> {

    @Autowired
    private BabyAccountMapper babyMapper;

    @Autowired
    private BabyIconImageMapper babyIconImageMapper;

    @Autowired
    private UserRelationshipMapper userRelationshipMapper;

    @Autowired
    private BabyRelationshipMapper babyRelationshipMapper;

    @Autowired
    private UserRelationshipNameMapper userRelationshipNameMapper;

    @Autowired
    private UserRelationshipCandyMapper userRelationshipCandyMapper;

    @Autowired
    private UserRelationshipLogMapper userRelationshipLogMapper;

    @Autowired
    private BabyPartnerMapper babyPartnerMapper;

    @Autowired
    private BehaviorLogMapper behaviorLogMapper;

    @Autowired
    private BehaviorOperationImageMapper behaviorOperationImageMapper;

    @Autowired
    private CandyMapper candyMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${key}")
    private String key;
    @Value("${listKey}")
    private String listKey;

    /**
     * 增加baby的基本信息
     * @param babyAccountForm
     * @return
     */
    @Transactional
    public BabyAccountVO insertBabyAccountByCondition(BabyAccountForm babyAccountForm,UserRelationshipForm userRelationshipForm) throws FanCatException {
        if(EmptyUtil.isEmpty(babyAccountForm) && EmptyUtil.isEmpty(userRelationshipForm)){
            throw new FanCatException("参数异常", ErrorCode.parameters);
        }
        //判断user是否注册过baby，注册了几个baby，如果关系为父母的只能注册三个
        List<BabyRelationship> babyRelationshipFir = babyRelationshipMapper.selectOwnBaby(userRelationshipForm.getUserId());
        Integer counts = babyRelationshipFir.size();
        if (counts == 3) {
            throw new FanCatException("您已经注册3个baby了！",ErrorCode.hasBaby);
        }

        BabyAccountVO babyAccountVO = new BabyAccountVO();
        BabyAccount babyAccount = new BabyAccount();
        Date date = new Date();
        babyAccount.setBabyId(StringUtil.getUUID());
        babyAccount.setBirthday(babyAccountForm.getBirthday());
        babyAccount.setGender(babyAccountForm.getGender());  //性别,1男,2女
        babyAccount.setNickName(babyAccountForm.getNickName());
        babyAccount.setSurplusCandy(0);  //新增baby，初始化金额
        babyAccount.setTotalCandy(0);    //新增baby，初始化金额
        babyAccount.setUpdateTime(date);
        babyAccount.setCreateTime(date);
        int number = babyMapper.insert(babyAccount);
        if(number == 0){
            throw new FanCatException("添加宝宝失败",ErrorCode.addBabyError);
        }
        BabyAccount baby = null;
        if(number > 0){
            baby = babyMapper.selectById(babyAccount);

            //在baby关系表中建立关系
            BabyRelationship babyRelationship = new BabyRelationship();
            babyRelationship.setBabyId(baby.getBabyId());
            babyRelationship.setUserId(userRelationshipForm.getUserId());
            babyRelationship.setType(0); //自己创建
            babyRelationship.setState(0);
            babyRelationship.setRelationship(userRelationshipForm.getRelationship());
            babyRelationship.setCreateTime(date);
            babyRelationship.setUpdateTime(date);
            babyRelationshipMapper.insert(babyRelationship);  //插入baby关系表

            //创建userLog账户和candy账户
            UserRelationshipCandy userRelationshipCandy = new UserRelationshipCandy();   //新用户，添加至数据库中,这是糖果币账户
            userRelationshipCandy.setUserId(userRelationshipForm.getUserId());
            userRelationshipCandy.setBabyId(baby.getBabyId());
            userRelationshipCandy.setIncreaseCandy(0);
            userRelationshipCandy.setReduceCandy(0);
            userRelationshipCandy.setCreateTime(date);
            userRelationshipCandy.setUpdateTime(date);
            userRelationshipCandyMapper.insert(userRelationshipCandy);

            UserRelationshipLog userRelationshipLog = new UserRelationshipLog();//新用户，添加至数据库中log表
            userRelationshipLog.setUpdateTime(date);
            userRelationshipLog.setCreateTime(date);
            userRelationshipLog.setAfterCandy(0);
            userRelationshipLog.setBeforeCandy(0);
            userRelationshipLog.setCandy(0);
            userRelationshipLog.setOperType(1);
            userRelationshipLog.setUserId(userRelationshipForm.getUserId());
            userRelationshipLog.setBabyId(baby.getBabyId());
            userRelationshipLogMapper.insert(userRelationshipLog);

            //新用户注册，小程序⽤户首次授权并创建宝宝信息，+500糖果币  先修改babyAccount的账户SurplusCandy，TotalCandy
            Candy candy = candyMapper.selectCandy();
            babyMapper.modifyCandy(candy.getRegisterCandy(),baby.getBabyId());
            //在修改当前user——candy的账户信息
            userRelationshipCandyMapper.modifyCandy(candy.getRegisterCandy(),userRelationshipForm.getUserId(),baby.getBabyId());
            //在修改当前user——log的账户信息,先查询当前baby的账户金额，然后修改相应的信息
            //当前不需查询baby的金额是因为刚创建的用户默认账户里面是0；
            userRelationshipLogMapper.modifyCandy(candy.getRegisterCandy(),userRelationshipForm.getUserId(),0,baby.getBabyId());
        }

        try {
            BeanUtils.copyProperties(babyAccountVO,baby);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return babyAccountVO;
    }

    /**
     * 查询宝宝的基本信息
     * @param userRelationshipForm
     * @return
     *
     */
    public BabyAccountVO selectBabyAccountByCondition(UserRelationshipForm userRelationshipForm) throws FanCatException {
        if(EmptyUtil.isEmpty(userRelationshipForm.getBabyId()) || EmptyUtil.isEmpty(userRelationshipForm.getUserId())){
            throw new FanCatException("参数异常",ErrorCode.parameters);
        }

        //判断Redis中是否含有key
        BabyRelationship babyRelationship = babyRelationshipMapper.selectBabyByUidAndBid(userRelationshipForm.getUserId(),userRelationshipForm.getBabyId());
        if(EmptyUtil.isEmpty(babyRelationship)){
            throw new FanCatException("该用户下没有宝宝信息，请添加",ErrorCode.addBaby);
        }

//        //查询Redis中是否含有key
//        String babyId = babyRelationship.getBabyId();
//        if(EmptyUtil.isNotEmpty(redisUtil.get(key+babyId+userRelationshipForm.getUserId()))){
//            return (BabyAccountVO) redisUtil.get(key+babyId+userRelationshipForm.getUserId());
//        }

        BabyAccountVO babyAccountVO = new BabyAccountVO();

        BabyAccount babyAccount = new BabyAccount();
        babyAccount.setBabyId(babyRelationship.getBabyId());
        BabyAccount baby = babyMapper.selectOne(babyAccount);
        babyAccountVO.setBirthday(baby.getBirthday());
        babyAccountVO.setGender(baby.getGender());
        babyAccountVO.setNickName(baby.getNickName());
        babyAccountVO.setRank(this.babyRank(babyRelationship.getBabyId()));
        babyAccountVO.setSurplusCandy(baby.getSurplusCandy());
        babyAccountVO.setTotalCandy(baby.getTotalCandy());
        babyAccountVO.setRelationship(babyRelationship.getRelationship());
        //查询关系名称
        String relationName = userRelationshipNameMapper.selectName(babyRelationship.getRelationship()).getRelationshipName();
        babyAccountVO.setRelationshipName(relationName);
        // 通过用户ID查询(baby's icon)
        BabyIconImage entity = new BabyIconImage();
        entity.setBabyId(babyRelationship.getBabyId());
        babyAccountVO.setImage(babyIconImageMapper.selectOne(entity).getImage());

        //查询baby亲人总数
        Integer counts = babyRelationshipMapper.sumKinsfolks(babyRelationship.getBabyId());
        babyAccountVO.setKinsfolksCounts(counts);
//        //存放Redis中
//        redisUtil.set(key+babyId+userRelationshipForm.getUserId(),babyAccountVO);

        return babyAccountVO;
    }


    /**
     * 修改宝宝基本信息
     * @param userRelationshipForm
     * @return
     */
    @Transactional
    public BabyAccount modifyBabyAccountByCondition(UserRelationshipForm userRelationshipForm,BabyAccountForm babyAccountForm) throws FanCatException {
        if(null == userRelationshipForm){
            throw new FanCatException("参数异常",ErrorCode.parameters);
        }

        BabyRelationship babyRelationship = babyRelationshipMapper.selectBabyByUidAndBid(userRelationshipForm.getUserId(),userRelationshipForm.getBabyId());

        BabyAccount babyAccount = new BabyAccount();
        babyAccount.setBabyId(babyRelationship.getBabyId());
        babyAccount.setNickName(babyAccountForm.getNickName());
        babyAccount.setGender(babyAccountForm.getGender());
        babyAccount.setBirthday(babyAccountForm.getBirthday());
        babyAccount.setUpdateTime(new Date());

        babyMapper.modifyBabyInfo(babyAccount);

//        //操作Redis
//        String babyId = babyRelationship.getBabyId();
//        Set<String> keys = redisTemplate.keys(key + babyId + "*");
//        redisTemplate.delete(keys);

        return babyMapper.selectByBid(babyAccount.getBabyId());
    }


    /**
     * 查询亲人列表(我的个人信息页面)
     * @param userRelationshipForm
     * @return
     */
    public List<UserRelationshipBO> selectUserListByBabyId(UserRelationshipForm userRelationshipForm) throws FanCatException {
        if(EmptyUtil.isEmpty(userRelationshipForm.getUserId()) || EmptyUtil.isEmpty(userRelationshipForm.getBabyId())){
            throw new FanCatException("参数异常",ErrorCode.parameters);
        }

        //查询亲人列表
        List<BabyRelationship> listBaby = babyRelationshipMapper.selectUserListByBabyId(userRelationshipForm.getBabyId());
        List<UserRelationshipBO> listUser = new ArrayList<>();
        for(int i=0; i < listBaby.size(); i++){
            UserRelationshipCandy userAddCandy = userRelationshipCandyMapper.selectAddCandyById(listBaby.get(i).getUserId(),listBaby.get(i).getBabyId());
            //爸爸，妈妈一定要查询出来
            //有收入的亲人要查询出来
            if((listBaby.get(i).getRelationship()==1 || listBaby.get(i).getRelationship()==2) || userAddCandy.getIncreaseCandy() != 0){
                //user Info
                UserRelationshipBO userRelationshipBO = new UserRelationshipBO();
                BabyRelationship babyRelationship = babyRelationshipMapper.selectBabyByUidAndBid(listBaby.get(i).getUserId(),listBaby.get(i).getBabyId());
                UserRelationship userRelationship = userRelationshipMapper.selectUserInfoById(listBaby.get(i).getUserId());
                if(listBaby.get(i).getUserId().equals(userRelationshipForm.getUserId()) ){
                    userRelationship.setName("我");
                }
                //user relationName
                UserRelationshipName userRelationshipName = new UserRelationshipName();
                userRelationshipName.setRelationship(babyRelationship.getRelationship());
                UserRelationshipName u = userRelationshipNameMapper.selectOne(userRelationshipName);

                //user candy
                UserRelationshipCandy userRelationshipCandy = new UserRelationshipCandy();
                userRelationshipCandy.setUserId(babyRelationship.getUserId());
                userRelationshipCandy.setBabyId(babyRelationship.getBabyId());
                UserRelationshipCandy ursc = userRelationshipCandyMapper.selectOne(userRelationshipCandy);

                //user image;

                userRelationshipBO.setBabyId(babyRelationship.getBabyId());
                userRelationshipBO.setName(userRelationship.getName());
                userRelationshipBO.setUserId(userRelationship.getUserId());
                userRelationshipBO.setIncreaseCandy(ursc.getIncreaseCandy());
                userRelationshipBO.setRelationshipName(u.getRelationshipName());
                userRelationshipBO.setImage(userRelationship.getIcon());
                listUser.add(userRelationshipBO);
            }

        }

        return listUser;
    }

    /**
     * 计算宝宝在伙伴圈的排名
     * @param babyId
     * @return
     */
    public Integer babyRank(String babyId) throws FanCatException {
        if(EmptyUtil.isEmpty(babyId)){
            throw new FanCatException("参数异常",ErrorCode.parameters);
        }
        Integer rank = 1;
        List<BabyPartner> partnersList = babyPartnerMapper.selectBabyPartnerByBid(babyId);
        if(EmptyUtil.isEmpty(partnersList)){
           rank = 0;
           return rank;
        }

        //查询该baby的总金额
        BabyAccount baby = babyMapper.selectByBid(babyId);
        Integer candys = baby.getTotalCandy();

        for(int i = 0;i < partnersList.size();i++){
            BabyAccount babyAccount = babyMapper.selectByBid(partnersList.get(i).getAssociatedBabyId());
            Integer money = babyAccount.getTotalCandy();
            if(candys < money){
                rank++;
            }
        }

        return rank;
    }


    /**
     * 查询所有的关系名称和编号
     * @return
     */
    public List<UserRelationshipName> selectNames(){
        return userRelationshipNameMapper.selectAllNames();
    }

    /**
     * 判断账户状态是否合法
     * @param id
     * @param status
     * @return
     * @throws Exception
     */
    public BabyAccount onOff(String id, Integer status) throws FanCatException{
        BabyAccount babyAccount = babyMapper.selectByBid(id);
        AccountStatus temp = AccountStatus.getEnumByStatus(status);
        if(EmptyUtil.isEmpty(temp)){
            throw new FanCatException("账户状态非法：不是0或1",ErrorCode.statusError);
        }
        babyAccount.setStatus(status);
        babyMapper.modifyBabyInfo(babyAccount);
        return babyAccount;
    }

    /**
     * 查询该user下所有baby的列表
     * @param userId
     * @return
     * @throws FanCatException
     */
    public List<BabyAccountVO> selectBabyList(String userId) throws FanCatException {
        if(EmptyUtil.isEmpty(userId)){
            throw new FanCatException("参数异常",ErrorCode.parameters);
        }
        List<BabyAccountVO> list = new ArrayList<>();

        List<BabyRelationship> babyRelationshipList = babyRelationshipMapper.selectOwnBabyList(userId);
        babyRelationshipList.stream().forEach(baby -> {
            BabyAccountVO babyAccountVO = new BabyAccountVO();
            babyAccountVO.setBabyId(baby.getBabyId());
            BabyAccount babyAccount = babyMapper.selectByBid(baby.getBabyId());
            babyAccountVO.setNickName(babyAccount.getNickName());
            babyAccountVO.setRelationship(baby.getRelationship());
            babyAccountVO.setRelationshipName(userRelationshipNameMapper.selectName(baby.getRelationship()).getRelationshipName());
            babyAccountVO.setImage(babyIconImageMapper.selectByBid(baby.getBabyId()).getImage());
            list.add(babyAccountVO);
        });
        return list;
    }

    public Page<BabyAccount> selectBabyInfo(BabyAccountForm babyAccountForm) {
        BabyAccount babyAccount = new BabyAccount();
        org.springframework.beans.BeanUtils.copyProperties(babyAccountForm,babyAccount); //前面赋值给后面
        Page<BabyAccount> page = new Page<BabyAccount>(babyAccountForm.getPageNo(), babyAccountForm.getPageSize());
        page.setRecords(babyMapper.selectBabyInfo(page,babyAccount));
        return page;
    }

    public PageList getByBabyId(String id, Integer pageNo, Integer pageSize) {
        PageList page = new PageList();
        List list = selectOperationImages(id);
        page.setCurrentPage(pageNo);
        //设置每页数据为十条
        page.setPageSize(12);
        //每页的开始数
        page.setStar((page.getCurrentPage() - 1) * page.getPageSize());
        //list的大小
        int count = list.size();
        //设置总页数
        page.setTotalPage(count);
        //对list进行截取
        page.setDataList(list.subList(page.getStar(),count-page.getStar()>page.getPageSize()?page.getStar()+page.getPageSize():count));
        //设置作用域
        return page;
    }



    public List selectOperationImages(String babyId) {
        List<BabyRelationship> babyRelationships = babyRelationshipMapper.selectUserListByBabyId(babyId);
        //List<List<BehaviorOperationImage>> b = new ArrayList<>();
        List<BehaviorOperationImage> b = new ArrayList<>();
        for(BabyRelationship babyUser : babyRelationships) {
            List<String> operationIds = behaviorLogMapper.selectOperationIds(babyUser.getUserId());
            for(String operationId : operationIds) {
                List<BehaviorOperationImage> behaviorOperationImages = behaviorOperationImageMapper.selectBehaviorOperationImages(operationId);
                for(BehaviorOperationImage bb : behaviorOperationImages) {
                    b.add(bb);
                }
                //b.add(behaviorOperationImages);
            }
        }
        return b;
    }


}
